import { BrowserRouter, Route, Routes, Navigate, useLocation } from 'react-router-dom'
import Page, {changeMenuList} from './page'
import { getCookie } from '../utils'
import React, { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'



const Router = () => {

    const [page, setPage]= useState(Page)

    const menuList = useSelector(state => state.menuList)

    
    useEffect(() => {
        setPage(changeMenuList(menuList))
    }, [menuList])

    const BeforeEach = (props) => {

        const location = useLocation();

        if (!getCookie() && location.pathname !== '/login') {
            return <Navigate to="/login" />
        }

        return props.children
    }


    const renderRouter = (routes) => {
        return routes.map((item, idx) => {
            return item.path ? <Route key={idx} path={item.path} element={<BeforeEach>{item.element}</BeforeEach>} >
                {
                    item.children && renderRouter(item.children)
                }
            </Route> : <Route key={idx} path={item.from} element={<Navigate to={item.to} />} ></Route>
        })
    }


    return <BrowserRouter>
        <Routes>
            {
                renderRouter(page)
            }
        </Routes>
    </BrowserRouter>
}

export default Router